import React, { useState, useRef, useMemo, useCallback } from 'react';
import useIOSActive from '@y.dsh/hooks/lib/useIOSActive';
import Scroll from '../src';
import { ScrollMethods } from '../types';
import { getData10 } from './utils';
import Item from './Item';
import './styles/app.scss';

function App(): JSX.Element {
  useIOSActive(); // 激活ios active事件

  const scrollViewRef = useRef<ScrollMethods>();

  const getData = useMemo(() => getData10(), []);
  const [data, setData] = useState<{ id: string, text: string }[]>(getData.create());

  /**
   * 下拉刷新
   */
  const refreshCount = useRef(0);
  const refreshing = useCallback(
    () => {
      refreshCount.current += 1;
      setTimeout(() => { // 模拟接口
        if (scrollViewRef.current) {
          if (refreshCount.current % 3 !== 0) { // 成功时刷新数据
            setData(getData.create());
          }
          scrollViewRef.current.downComplete({
            // 不论成功或者失败 都需要调用刷新完成函数 否则将停滞在刷新中
            success: refreshCount.current % 3 !== 0 // 参数为是否成功 success boolean
          });
        }
      }, 1000);
    },
    [getData],
  );

  /**
   * 上拉加载
   */
  const loadCount = useRef(0);
  const loading = useCallback(
    () => {
      loadCount.current += 1;
      setTimeout(() => {
        if (scrollViewRef.current) {
          if (loadCount.current !== 3) {
            setData(prevState => ([
              ...prevState,
              ...getData.create()
            ]));
          }
          scrollViewRef.current.loadComplete({
            // 需要调用加载完成函数 否则将停滞在加载中
            success: loadCount.current !== 3, // 参数为是否成功 success boolean
            end: loadCount.current === 5 // 参数为是否到底了 end boolean
          });
        }
      }, 2000);
    },
    [getData],
  );

  return (
    <Scroll
      ref={scrollViewRef}
      down={{ refreshing }}
      up={{ loading }}
      side={{
        button: [
          {
            children: '说明',
            onTap() {
              // explain();
              alert('11')
            }
          },
          { inlayType: 'theTop' }
        ]
      }}
    >
      <ul className="scroll-view-list" style={{ fontSize: 24 }}>
        {data.map(item => <Item key={item.id} data={item} />)}
      </ul>
      <div>
        <img
          style={{ display: 'block', width: '100%', marginTop: 10 }}
          data-lazy="https://ss3.bdstatic.com/70cFv8Sh_Q1YnxGkpoWK1HF6hhy/it/u=240310730,3135775327&fm=26&gp=0.jpg"
          alt=""
        />
      </div>
    </Scroll>
  )
}

export default App
